package com.android.svmc.app.mobile.activity;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.Window;
import android.widget.TextView;
import android.widget.Toast;

import com.android.svmc.app.mobile.controller.CheckNewRecordService;
import com.android.svmc.app.mobile.controller.SaveDataService;
import com.android.svmc.app.mobile.controller.WifiManagement;
import com.android.svmc.app.mobile.data.JsonData;
import com.android.svmc.app.mobile.model.MenuItem;
import com.android.svmc.app.mobile.model.PictureModel;
import com.android.svmc.app.mobile.tabmanager.TabMain;
import com.android.svmc.app.mobile.util.CommonDefine;
import com.android.svmc.app.mobile.util.SettingUtils;
import com.android.svmc.app.mobile.view.CustomDialog;





public class Splash extends Activity implements CommonDefine {
	static ArrayList<MenuItem> listcategory;
	static ArrayList<PictureModel> listpicture;
	CustomDialog mydialog;
	private getBackgroudListCategory getlistcategory;
	private getListCategoryOffline getlistcategory_Offline;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.splash_320);
		TextView tv = (TextView) findViewById(R.id.textView1);
		Typeface font = Typeface.createFromAsset(getAssets(),
				"font/Museo900-Regular.otf");
		tv.setTypeface(font);
		// prepareData();
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

	}

	@Override
	protected void onResume() {
		super.onResume();
		prepareData();
	}

	private void prepareData() {
		SharedPreferences mPreferences = PreferenceManager
				.getDefaultSharedPreferences(this);
		boolean firstTime = mPreferences.getBoolean("firstTime_app", true);
		if (firstTime) {
			SharedPreferences.Editor editor = mPreferences.edit();
			editor.putBoolean("firstTime", false);
			editor.commit();
			defaultSetting();
		}

		/**********************************************************************
		 * PREPARE DATA WHEN START APPS
		 **********************************************************************/
		WifiManagement.getInstance(getApplicationContext());
		if (WifiManagement.haveNetworkConnection() == true) {
			showToast("Kết nối mạng đã sẵn sàng ");
			if (mydialog != null && mydialog.isShowing()) {
				mydialog.dismiss();
			}
			// Handler handleSplash = new Handler();
			// handleSplash.postDelayed(new WelcomeScreen(), SPLASH_TIME);
			// new getBackgroudListCategory().execute();
			getlistcategory = new getBackgroudListCategory();
			getlistcategory.execute();

		} else if (SettingUtils.getbooleanPreferences(this, IS_OFFLINE_MODE) == true) {
			showToast("Không có kết nối mạng.Chế độ Offline được bật");
			if (mydialog != null && mydialog.isShowing()) {
				mydialog.dismiss();
			}
			Handler handleSplash = new Handler();
			handleSplash.postDelayed(new WelcomeScreenOffline(), SPLASH_TIME);
		} else {
			mydialog = new CustomDialog(this);
			mydialog.setDialogType(DIALOG_INFO_NETWORK,
					getString(R.string.message_network_error));
			mydialog.setOnKeyListener(new OnKeyListener() {
				// disable back key.
				@Override
				public boolean onKey(DialogInterface dialog, int keyCode,
						KeyEvent event) {
					// TODO Auto-generated method stub
					if (keyCode == KeyEvent.KEYCODE_BACK
							&& event.getAction() == KeyEvent.ACTION_UP)
						finish();
					return false;
				}
			});
			mydialog.show();

		}

		Intent intent = new Intent(this, CheckNewRecordService.class);
		if (SettingUtils.getbooleanPreferences(this, IS_STARTED_SERVICE_NOTIFICATION) == false
				&& SettingUtils.getbooleanPreferences(this, IS_NOTIFICATION) == true) {
			startService(intent);
		}
		
		/**********************************************************************
		 * FINISH PREPARE --> JUMP TO NEXT SCREEN
		 **********************************************************************/

	}
	private class WelcomeScreenOffline implements Runnable {
		public void run() {
			getlistcategory_Offline = new getListCategoryOffline();
			getlistcategory_Offline.execute();
		}
	}

	private void defaultSetting() {
		SettingUtils.savebooleanPreferences(this, IS_ROTATION_SCREEN, false);
		SettingUtils.savebooleanPreferences(this, IS_NOTIFICATION, true);
		SettingUtils.savebooleanPreferences(this, IS_OFFLINE_MODE, true);
		SettingUtils.savebooleanPreferences(this, IS_SYNC_DIARY, false);

	}
	private String getDataOffline (){
		InputStream iS = getResources().openRawResource(R.raw.data_offline);
		ByteArrayOutputStream oS = new ByteArrayOutputStream();
		try {
			byte[] buffer = new byte[iS.available()];
			iS.read(buffer);
			oS.write(buffer);
			oS.close();
			iS.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return oS.toString();
	}
	public class getListCategoryOffline extends AsyncTask<Void, Void, Void>{

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			String data = getDataOffline();
			JsonData json = new JsonData(Splash.this);
			listcategory = json.getListCategory(data, false);
			return null;
		}
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Intent i = new Intent(getApplication(), TabMain.class);
			Splash.this.startActivity(i);
			Splash.this.finish();
		}
		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			
		}
	}

	public class getBackgroudListCategory extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			JsonData json = new JsonData(Splash.this);
			try {
				listcategory = json.getListCategory("",true);
				// listpicture = json.getAllPicture(DEFAULT_ID, 1);
			} catch (NullPointerException g) {
				// TODO: handle exception
			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			Intent i = new Intent(getApplication(), TabMain.class);
			Splash.this.startActivity(i);
			Splash.this.finish();

		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

	}

	public void showToast(String message) {
		Toast.makeText(this, message, Toast.LENGTH_LONG).show();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		if (mydialog != null && mydialog.isShowing()) {
			mydialog.cancel();
		}
		if (getlistcategory != null && getlistcategory.isCancelled()) {
			getlistcategory.cancel(true);
		}
		if(getlistcategory_Offline !=null && getlistcategory_Offline.isCancelled()){
			getlistcategory_Offline.cancel(true);
		}
	}

}
